public class SingleQueue {
    public int[] arr = new int[5];
    public int head = 0;
    public int tail = 0;
    public int size = 0;
    public void put(int val) throws InterruptedException {
        synchronized (this){
            if(size == arr.length){
                wait();
            }
            arr[tail] = val;
            size++;
            tail = (tail+1)%arr.length;
            notify();
        }
    }
    public int take() throws InterruptedException {
        synchronized (this){
            if(size == 0){
                wait();
            }
            int tmp = arr[head];
            size--;
            head = (head+1)%arr.length;
            notify();
            return tmp;
        }
    }
    synchronized public int getSize(){
        return size;
    }
    static int i = 0;
    public static void main(String[] args) {
        SingleQueue singleQueue = new SingleQueue();
        Thread t1 = new Thread(() -> {
            while (true){
                try {
                    singleQueue.put(i);
                    System.out.println("生产"+i);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                i++;
            }
        });
        Thread t2 = new Thread(() -> {
            while (true){
                try {
                    Thread.sleep(100);
                    System.out.println("消费"+singleQueue.take());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
    }
}
